/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import utils.DbManager;
import utils.Prodotti;
import utils.Utilizzatore;


/**
 *
 * @author Alice
 */
public class Aggiunta_Prodotti extends HttpServlet {
        private DbManager manager;
       // private String dirName;
    
 @Override
public void init() throws ServletException {
// inizializza il DBManager dagli attributi di Application
this.manager = (DbManager)super.getServletContext().getAttribute("dbmanager");
}
 
 /**public void init(ServletConfig config) throws ServletException {
        super.init(config);
        // read the uploadDir firom the servlet parameters
        dirName = config.getInitParameter("ImgProdDir");
        if (dirName == null) {
        throw new ServletException("Please supply uploadDir parameter");
    }}*/
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, NumberFormatException {
        HttpSession session = request.getSession(false);
        if(session.getAttribute("user")==null)
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        
        try {
        String nomeprod= request.getParameter("nomeprodotto");
        String descrizione=request.getParameter("descrizione");
        String categoria= request.getParameter("categoria");
        String venditore= request.getParameter("venditore");
        String qu= request.getParameter("quantita");
        int quant=Integer.parseInt(qu);
        String gi= request.getParameter("gg");
        int gg=Integer.parseInt(gi);
        String m= request.getParameter("mm");
        int mm=Integer.parseInt(m);
        String a= request.getParameter("aaaa");
        int aaaa=Integer.parseInt(a);
        String h= request.getParameter("hh");
        int hh=Integer.parseInt(h);
        String mi= request.getParameter("min");
        int min=Integer.parseInt(mi);
        int sec=00;
        //String s= aaaa+"-"+mm+"-"+gg+" "+hh+":"+min+":00";
        //String ss=String.valueOf(s);
        //Timestamp scadenza= Timestamp.valueOf(aaaa+"-"+mm+"-"+gg+" "+hh+":"+min+":00");
        //Timestamp ts=new Timestamp(aaaa,mm,gg,hh,min,sec,0);
        //System.out.println("timestamp"+s);
        
       ///SCADENZA!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 
      
      Date date = null;
      Timestamp scadenza = null;
                    try {
                        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
                        date = dateFormat.parse(aaaa+"/"+mm+"/"+gg+" "+hh+":"+min+":"+sec);
                        long timee = date.getTime();
                        scadenza=new Timestamp(timee);   
                        System.out.println("SCAD= "+scadenza);
                    } catch (ParseException ex) {
                        Logger.getLogger(Aggiunta_Prodotti.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    
      
System.out.println("SCAD= "+scadenza);
        String of= request.getParameter("offerta");
        float offerta=Float.parseFloat(of);
        String iM= request.getParameter("incrementoMin");
        float incrMin=Float.parseFloat(iM);
        String pSped= request.getParameter("prezzoSpediz");
        float prezSped=Float.parseFloat(pSped);
        
        String urlimg= request.getParameter("sfoglia");
        if ("".equals(urlimg))urlimg="NO PHOTO";
        System.out.println("dati:"+nomeprod+categoria+venditore+quant+offerta+incrMin+prezSped+urlimg);
            
    
        //ServletContext ctx=request.getServletContext();
        //String contextPath=ctx.getRealPath(File.separator);
    
       //CREA CARTELLA
      /**  File file= new File(contextPath+"ImgPROD/");
        if(!file.exists()){
            file.mkdir();
        }*/
    /**  String cartellaOUT=(contextPath+"ImgPROD/");
        System.out.println("CARTELLAOUT= "+cartellaOUT);  
      MultipartRequest multi;
      multi = new MultipartRequest(request,"/ImgPROD/");
        System.out.println("MULTI= "+multi);
      String par;
      par = (String)multi.getParameter("sfoglia");
        System.out.println("PAR= "+par);
     // File f = multi.getFile("img");
      
File image = new File(request.getParameter("sfoglia"));

       // System.out.println("F= "+f);
if (image==null) {
      response.sendRedirect("error.jsp");
}else{
    String[] store = multi.getParameterValues("sfoglia");
String fileName = multi.getFilesystemName("IMAGE");
if (store==null) {
//costruisco il path assoluto in cui memorizzare
//l’immagine il metodo System.getenv() permette di
//recuperare il valore di una variabile d’ambiente.
//Il file viene memorizzato in una sottocartella "uploads"
String filepath = f + fileName;
File fOUT = new File(filepath);
//scrivo in fOUT il file f

      File fIN = new File(par);
      FileInputStream fIS = new FileInputStream(fIN);
      FileOutputStream fOS = new FileOutputStream(fOUT);
// copio byte per byte l ’ i m m a g i n e dallo stream
// in i n g r e s s o a quello in uscita
      while (fIS.available()>0)
        fOS.write(fIS.read());
// chiudo gli stream
      fIS.close();
      fOS.close();
        
//inoltro un errore da visualizzare alla JSP


//--> DB FILEPATH
 //memorizzo nel DB direttamente l’immagine
//dbms.storePeoplePicture(name,surname,f);
*/


        
         Date data=new Date();
            Timestamp time=new Timestamp(data.getTime());
   System.out.println("timep"+time);
            List<Prodotti> productSeller = manager.newProducts(nomeprod,descrizione,categoria,venditore,quant,scadenza,offerta,incrMin,prezSped,urlimg,time);
            
        } catch (SQLException ex) {
            Logger.getLogger(Aggiunta_Prodotti.class.getName()).log(Level.SEVERE, null, ex);
            String message="Errore !";
            response.sendRedirect("utilizzatore/aggiungiprodotto_utilizzatore.jsp?message"+URLEncoder.encode(message, "UTF-8"));
        }
        String message="Prodotto Inserito !";
        Utilizzatore user=(Utilizzatore)session.getAttribute("user");
        String nome=user.getNome(); String cognome=user.getCognome();
        
            response.sendRedirect("utilizzatore/aggiungiprodotto_utilizzatore.jsp?user="+nome+" "+cognome+"&message="+URLEncoder.encode(message, "UTF-8"));
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
